package com.springmvc.servlet;

import com.springmvc.base.Handler;
import com.springmvc.base.HandlerAdaptor;
import com.springmvc.base.HandlerMapping;
import com.springmvc.base.ViewResolver;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet extends HttpServlet {

    private HandlerMapping handlerMapping;

    @Override
    public void init() throws ServletException {
        try {
            System.out.println("初始化=================================================");
            String configLocation = this.getServletConfig().getInitParameter("configLocation");
            InputStream in = this.getClass().getClassLoader().getResourceAsStream(configLocation);
            SAXReader reader = new SAXReader();
            Document document = reader.read(in);
            Element root = document.getRootElement();
            List<Element> elements = root.elements("bean");
            List<Object> beans = new ArrayList<>();
            for (Element element : elements) {
                String className = element.attributeValue("className");
                Class<?> clazz = Class.forName(className);
                beans.add(clazz.newInstance());
            }
            handlerMapping = new HandlerMapping();
            handlerMapping.process(beans);
        } catch (DocumentException | ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void service(HttpServletRequest req,
                           HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String requestURI = req.getRequestURI();
        String contextPath = req.getContextPath();
        String url = requestURI.substring(contextPath.length());
        Handler handler = handlerMapping.getHandler(url);
        HandlerAdaptor handlerAdaptor = new HandlerAdaptor(handler);
        Object modelAndView = handlerAdaptor.getModelAndView(req,resp);
        ViewResolver viewResolver = new ViewResolver(modelAndView,handler);
        viewResolver.response(req,resp);
    }
}
